<template>
	<view class="page-container">
		<!-- 已登录状态 -->
		<view v-if="isLogin">
			<view class="userinfo">
				<view class="avatar-container">
					<image class="avatar" :src="avatar" mode="widthFix" lazy-load @error="handleAvatarError"></image>
					<view class="avatar-status"></view>
				</view>
				<view class="user-details">
					<text class="title">{{ user.nickname || user.name || user.userName || '默认用户' }}</text>
					<!-- 新增：展示脱敏手机号（可选，按需显示） -->
					<text class="subtitle">{{ user.phone ? `手机号：${user.phone}` : '今天想吃点什么呢？' }}</text>
					<view class="member-progress">
						<view class="progress-bar">
							<view class="progress-fill" :style="{width: `${user.progress ?? 75}%`}"></view>
						</view>
						<text class="progress-desc">{{ user.score ?? 120 }}积分/{{ user.targetScore ?? 160 }}积分升级</text>
					</view>
				</view>
				<view class="member-badge">
					<text class="badge-text">{{ user.memberLevel || '普通会员' }}</text>
				</view>
			</view>

			<view class="user-benefit">
				<view class="benefit-item" @click="navigateTo('/pages/coupon/list')">
					<text class="benefit-icon">💰</text>
					<text class="benefit-text">会员券包</text>
					<text class="benefit-count">{{ user.voucherCount ?? 0 }}张可用</text>
				</view>
				<view class="benefit-item" @click="navigateTo('/pages/score/index')">
					<text class="benefit-icon">🎁</text>
					<text class="benefit-text">我的积分</text>
					<text class="benefit-count">{{ user.score ?? 0 }}分</text>
				</view>
				<view class="benefit-item" @click="navigateTo('/pages/coupon/discount')">
					<text class="benefit-icon">🎫</text>
					<text class="benefit-text">优惠券</text>
					<text class="benefit-count">{{ user.couponCount ?? 0 }}张</text>
				</view>
				<view class="benefit-item" @click="navigateTo('/pages/card/list')">
					<text class="benefit-icon">⭐</text>
					<text class="benefit-text">我的卡券</text>
					<text class="benefit-count">{{ user.cardCount ?? 0 }}张</text>
				</view>
			</view>

			<view class="order-status">
				<view class="status-header">
					<text class="status-title">我的订单</text>
					<text class="view-all" @click="navigateTo('/pages/order/list')">查看全部 ></text>
				</view>
				<view class="status-grid">
					<view class="status-item" @click="navigateTo('/pages/order/list?type=pending')">
						<view class="status-icon pending">
							<text class="icon-text">📦</text>
						</view>
						<text class="status-text">待付款</text>
					</view>
					<view class="status-item" @click="navigateTo('/pages/order/list?type=delivering')">
						<view class="status-icon delivering">
							<text class="icon-text">🚚</text>
						</view>
						<text class="status-text">配送中</text>
					</view>
					<view class="status-item" @click="navigateTo('/pages/enter/review?type=review')">
						<view class="status-icon review">
							<text class="icon-text">✏️</text>
						</view>
						<text class="status-text">待评价</text>
					</view>
					<view class="status-item" @click="navigateTo('/pages/order/list?type=refund')">
						<view class="status-icon refund">
							<text class="icon-text">🔄</text>
						</view>
						<text class="status-text">退款/售后</text>
					</view>
				</view>
			</view>

			<view class="menu-container">
				<view class="menu-group">
					<view class="menu-item" @click="navigateTo('/pages/user/history')">
						<view class="menu-icon">👀</view>
						<view class="menu-text">浏览记录</view>
						<view class="menu-arrow">→</view>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/address/addressList')">
						<view class="menu-icon">🏠</view>
						<view class="menu-text">收货地址</view>
						<view class="menu-arrow">→</view>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/user/favorites')">
						<view class="menu-icon">❤️</view>
						<view class="menu-text">我的收藏</view>
						<view class="menu-arrow">→</view>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/user/profile')">
						<view class="menu-icon">👤</view>
						<view class="menu-text">个人资料</view>
						<view class="menu-arrow">→</view>
					</view>
					<view class="menu-item" @click="navigateTo('/pages/user/setting')">
						<view class="menu-icon">⚙️</view>
						<view class="menu-text">设置</view>
						<view class="menu-arrow">→</view>
					</view>
					<view class="menu-item logout-item" @click="handleLogout">
						<view class="menu-icon">🚪</view>
						<view class="menu-text">退出登录</view>
						<view class="menu-arrow">→</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 未登录状态 -->
		<view v-else>
			<view class="userinfo">
				<view class="avatar-container">
					<image class="avatar" :src="avatarDefault" mode="widthFix" lazy-load></image>
				</view>
				<view class="user-details" @click="handleLogin">
					<text class="title">登录 / 注册</text>
					<text class="subtitle">登录后享受更多点餐优惠</text>
				</view>
				<view class="login-hint" @click="handleLogin">
					<text class="hint-icon">→</text>
				</view>
			</view>

			<view class="login-prompt">
				<view class="prompt-content">
					<image class="prompt-icon" src="/static/images/food-truck.png" mode="widthFix" lazy-load
						@error="() => { this.src = '/static/images/default-prompt.png' }"></image>
					<view class="prompt-text">
						<view class="prompt-title">登录后享受完整服务</view>
						<view class="prompt-desc">查看订单、收藏店铺、管理地址</view>
					</view>
					<view class="login-benefit">
						<text class="benefit-tag">新人专享</text>
						<text class="benefit-desc">登录即领5元无门槛券</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getStorageToken,
		getStorageUser,
		removeStorageToken,
		setStorageUser
	} from "@/utils/storage.js";

	export default {
		data() {
			return {
				baseUrl: "http://localhost:5050",
				user: {},
				avatarDefault: "/static/images/avatar_default.png",
				avatar: "",
				isLogin: false
			};
		},

		onShow() {
			this.refreshUserInfo();
			if (this.isLogin) {
				this.fetchUserInfo();
			}
			// 绑定事件监听
			uni.$on("phoneUpdated", this.handlePhoneUpdate);
			uni.$on("userInfoUpdated", this.handleUserInfoUpdate);
		},

		onHide() {
			// 隐藏时清理监听
			uni.$off("phoneUpdated", this.handlePhoneUpdate);
			uni.$off("userInfoUpdated", this.handleUserInfoUpdate);
		},

		onUnload() {
			// 卸载时最终清理
			uni.$off("phoneUpdated");
			uni.$off("userInfoUpdated");
		},

		methods: {
			// 新增：手机号脱敏函数（与登录页规则一致）
			encryptPhone(phone) {
				if (!phone) return "";
				return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
			},

			refreshUserInfo() {
				this.user = getStorageUser() || {};
				// 补充：若缓存中手机号未脱敏，首次刷新时加密
				if (this.user.phone && !this.user.phone.includes("****")) {
					this.user.phone = this.encryptPhone(this.user.phone);
					setStorageUser(this.user);
				}
				this.avatar = this.user.avatar ? this.handleImgURL(this.user.avatar) : this.avatarDefault;
				this.isLogin = !!getStorageToken();
			},

			handleImgURL(url) {
				if (!url) return this.avatarDefault;
				return url.includes("http") ? url : `${this.baseUrl}${url.trim()}`;
			},

			fetchUserInfo() {
				const token = getStorageToken();
				if (!token) return;

				uni.request({
					url: `${this.baseUrl}/user/info`,
					method: "GET",
					header: {
						"Authorization": `Bearer ${token}`,
						"Content-Type": "application/json"
					},
					success: (res) => {
						// token失效处理
						if (res.statusCode === 401) {
							removeStorageToken();
							setStorageUser({});
							this.isLogin = false;
							uni.navigateTo({
								url: "/pages/user/login"
							});
							return;
						}

						if (res.statusCode === 200 && res.data.code === 200) {
							let backendUser = res.data.data || {};
							if (backendUser.username) backendUser.userName = backendUser.username;
							// 关键修改：获取用户信息时对手机号脱敏
							if (backendUser.phone) {
								backendUser.phone = this.encryptPhone(backendUser.phone);
							}
							backendUser.avatar = this.handleImgURL(backendUser.avatar);
							this.user = backendUser;
							this.avatar = this.user.avatar || this.avatarDefault;
							setStorageUser(this.user);
						}
					},
					fail: (err) => {
						console.error("用户信息请求失败：", err);
						uni.showToast({
							title: `网络错误：${err.errMsg}`,
							icon: "none",
							duration: 2000
						});
					}
				});
			},

			handleLogin() {
				uni.navigateTo({
					url: "/pages/user/login"
				});
			},

			navigateTo(url) {
				// 未登录拦截
				if (!this.isLogin) {
					uni.showToast({
						title: "请先登录",
						icon: "none"
					});
					return;
				}
				if (url) {
					uni.navigateTo({
						url
					});
				}
			},

			handleLogout() {
				uni.showModal({
					title: "确认退出",
					content: "确定要退出登录吗？",
					cancelText: "取消",
					confirmText: "确定",
					success: (res) => {
						if (res.confirm) {
							removeStorageToken();
							setStorageUser({});
							this.isLogin = false;
							this.user = {};
							this.avatar = this.avatarDefault;
							// 优化退出跳转
							uni.showToast({
								title: "退出成功",
								icon: "success",
								duration: 2000,
								success: () => {
									uni.reLaunch({
										url: "/pages/user/user"
									});
								}
							});
						}
					}
				});
			},

			// 头像加载失败处理
			handleAvatarError() {
				this.avatar = this.avatarDefault;
				this.user.avatar = this.avatarDefault;
			},

			// 手机号更新处理：新增脱敏逻辑
			handlePhoneUpdate(newPhone) {
				this.user.phone = this.encryptPhone(newPhone);
				setStorageUser(this.user);
			},

			// 用户信息更新处理：补充手机号脱敏
			handleUserInfoUpdate(newUserInfo) {
				this.user = newUserInfo;
				// 确保更新后的手机号已脱敏
				if (this.user.phone && !this.user.phone.includes("****")) {
					this.user.phone = this.encryptPhone(this.user.phone);
				}
				this.avatar = this.user.avatar || this.avatarDefault;
				setStorageUser(this.user);
			}
		}
	};
</script>

<style lang="scss">
	.page-container {
		min-height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
	}

	.userinfo {
		display: flex;
		align-items: flex-start;
		padding: 30rpx 20rpx;
		background: -webkit-linear-gradient(135deg, #ff9a44 0%, #ff6b6b 100%);
		background: linear-gradient(135deg, #ff9a44 0%, #ff6b6b 100%);
		box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
		position: relative;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			top: -50%;
			right: -50%;
			width: 100%;
			height: 100%;
			background: rgba(255, 255, 255, 0.15);
			border-radius: 50%;
			transform: scale(1.2);
		}

		.avatar-container {
			position: relative;
			margin-right: 20rpx;
			z-index: 2;

			.avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				border: 3rpx solid rgba(255, 255, 255, 0.3);
				box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
			}

			.avatar-status {
				position: absolute;
				bottom: 5rpx;
				right: 5rpx;
				width: 24rpx;
				height: 24rpx;
				border-radius: 50%;
				background: #4cd964;
				border: 2rpx solid white;
			}
		}

		.user-details {
			display: flex;
			flex-direction: column;
			z-index: 2;
			flex: 1;
			margin-top: 10rpx;

			.title {
				font-size: 30rpx;
				font-weight: 600;
				color: white;
				margin-bottom: 8rpx;
				text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
			}

			.subtitle {
				font-size: 22rpx;
				color: rgba(255, 255, 255, 0.9);
				margin-bottom: 10rpx;
			}

			.member-progress {
				width: 100%;
				margin-top: 10rpx;

				.progress-bar {
					width: 100%;
					height: 12rpx;
					background: rgba(255, 255, 255, 0.2);
					border-radius: 6rpx;
					overflow: hidden;

					.progress-fill {
						height: 100%;
						background: #ffd700;
						border-radius: 6rpx;
					}
				}

				.progress-desc {
					font-size: 18rpx;
					color: rgba(255, 255, 255, 0.8);
					margin-top: 5rpx;
				}
			}
		}

		.member-badge {
			background: -webkit-linear-gradient(135deg, #ffd700, #ffa500);
			background: linear-gradient(135deg, #ffd700, #ffa500);
			padding: 8rpx 16rpx;
			border-radius: 20rpx;
			box-shadow: 0 2px 8px rgba(255, 165, 0, 0.3);
			z-index: 2;
			margin-top: 20rpx;

			.badge-text {
				font-size: 20rpx;
				color: #7a5000;
				font-weight: 600;
			}
		}

		.login-hint {
			margin-left: 10rpx;
			z-index: 2;
			background: rgba(255, 255, 255, 0.25);
			border-radius: 50%;
			width: 48rpx;
			height: 48rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.hint-icon {
				font-size: 18rpx;
				color: white;
			}
		}
	}

	.user-benefit {
		display: flex;
		justify-content: space-around;
		background: #fff;
		padding: 20rpx 0;
		margin: 15rpx 0;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);

		.benefit-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 25%;
			padding: 10rpx 0;

			.benefit-icon {
				font-size: 36rpx;
				margin-bottom: 8rpx;
			}

			.benefit-text {
				font-size: 22rpx;
				color: #333;
			}

			.benefit-count {
				font-size: 20rpx;
				color: #ff6b6b;
				margin-top: 4rpx;
			}
		}
	}

	.order-status {
		background: white;
		margin: 0 15rpx 20rpx;
		border-radius: 16rpx;
		padding: 20rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

		.status-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 25rpx;

			.status-title {
				font-size: 26rpx;
				font-weight: 600;
				color: #333;
			}

			.view-all {
				font-size: 22rpx;
				color: #ff6b6b;
			}
		}

		.status-grid {
			display: flex;
			justify-content: space-around;

			.status-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				width: 25%;

				.status-icon {
					width: 70rpx;
					height: 70rpx;
					border-radius: 50%;
					margin-bottom: 10rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					.icon-text {
						font-size: 30rpx;
					}
				}

				.status-text {
					font-size: 22rpx;
					color: #666;
				}

				.pending {
					background: #fff2e8;

					.icon-text {
						color: #ff6b6b;
					}
				}

				.delivering {
					background: #e8f7ff;

					.icon-text {
						color: #3498db;
					}
				}

				.review {
					background: #f0f9ff;

					.icon-text {
						color: #2ecc71;
					}
				}

				.refund {
					background: #fff0f0;

					.icon-text {
						color: #e74c3c;
					}
				}
			}
		}
	}

	.menu-container {
		padding: 0 15rpx 20rpx;
		background: #f8f9fa;
		flex: 1;

		.menu-group {
			background: transparent;
		}

		.menu-item {
			display: flex;
			align-items: center;
			background: white;
			margin-bottom: 15rpx;
			border-radius: 12rpx;
			padding: 22rpx 25rpx;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

			.menu-icon {
				font-size: 30rpx;
				margin-right: 20rpx;
				width: 30rpx;
				text-align: center;
			}

			.menu-text {
				flex: 1;
				font-size: 26rpx;
				color: #333;
			}

			.menu-arrow {
				font-size: 24rpx;
				color: #ccc;
			}
		}

		.logout-item {
			.menu-text {
				color: #ff6b6b;
			}
		}
	}

	.login-prompt {
		margin: 40rpx 15rpx;
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		text-align: center;

		.prompt-content {
			display: flex;
			flex-direction: column;
			align-items: center;

			.prompt-icon {
				width: 120rpx;
				height: 120rpx;
				margin-bottom: 20rpx;
				opacity: 0.8;
			}

			.prompt-text {
				margin-bottom: 20rpx;

				.prompt-title {
					font-size: 26rpx;
					font-weight: 600;
					color: #333;
					margin-bottom: 10rpx;
				}

				.prompt-desc {
					font-size: 22rpx;
					color: #999;
				}
			}

			.login-benefit {
				display: flex;
				align-items: center;
				background: #fff2e8;
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				margin-bottom: 20rpx;

				.benefit-tag {
					font-size: 20rpx;
					color: #ff6b6b;
					font-weight: 600;
					margin-right: 8rpx;
				}

				.benefit-desc {
					font-size: 20rpx;
					color: #ff9a44;
				}
			}
		}
	}
</style>